package com.exercises;

import java.util.Arrays;
import java.util.Random;
import java.util.Stack;

public class Exercise32 {

    public static void main(String[] args) {
//        System.out.println(new Exercise32().longestValidParentheses("()"));
        int[] a = new int[]{1, 2, 3};
        for (int i = 0; i < 100; i++) {
            System.out.println(a[new Random().nextInt(a.length)]);
        }


    }

    public int longestValidParentheses(String s) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (stack.empty()) {
                stack.push(i);
            } else {
                int last = stack.lastElement();
                if (s.charAt(i) == ')' && s.charAt(last) == '(') {
                    stack.pop();
                } else {
                    stack.push(i);
                }
            }
        }
        if (stack.empty()) {
            return s.length();
        } else {
            int max = 0;
            int index = s.length();
            while (!stack.empty()) {
                int i = stack.pop();
                max = Math.max(max, index - i - 1);
                index = i;

            }
            return Math.max(max, index - 0);
        }
    }
}
